<template>
  <el-dialog class="setting drag-box-none" :title="$t('设置')" :visible.sync="visible" width="420px"
    :before-close="onClose">
    <el-form :model="userInfo" :label-width="currLanguage == 'en-US' ? '100px' : '100px'" :rules="rules"
      ref="settingForm" size="small" :label-position="currLanguage == 'en-US' ? 'left' : 'right'">
      <el-form-item :label="$t('头像')" style="margin-bottom: 0 !important;">
        <file-upload class="avatar-uploader" :action="imageAction" :showLoading="true" :maxSize="maxSize"
          @success="onUploadSuccess" :fileTypes="['image/jpeg', 'image/png', 'image/jpg', 'image/webp']">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </file-upload>
      </el-form-item>
      <el-form-item :label="$t('ID')">
        <el-input disabled v-model="userInfo.id"></el-input>
      </el-form-item>
      <el-form-item :label="$t('用户名')">
        <el-input disabled v-model="userInfo.account" autocomplete="off" size="small"></el-input>
      </el-form-item>
      <el-form-item :label="$t('自动删除消息')">
        <el-select class="select" v-model="userInfo.messageDeleteFlag" placeholder="自动删除消息"
          style="background-color: none;width:100%">
          <el-option v-for="item in autoDeleteList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="nickname" :label="$t('昵称')">
        <el-input v-model="userInfo.nickname" autocomplete="off" size="small"></el-input>
      </el-form-item>
      <el-form-item prop="sex" :label="$t('性别')">
        <el-radio-group v-model="userInfo.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="signature" :label="$t('个性签名')">
        <el-input type="textarea" v-model="userInfo.signature" :rows="3"></el-input>
      </el-form-item>
      <!-- <el-form-item label="地区">
        <el-cascader :props="addRessList" placeholder="请选择地址" @change="changeAddress"></el-cascader>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose()">{{ $t('取消') }}</el-button>
      <el-button type="primary" @click="onSubmit()">{{ $t('确定') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  countryList,
  provinceList,
  cityList
} from '@/api/userInfo.js'
let id = 0;
import FileUpload from "../common/FileUpload.vue";

export default {
  name: "setting",
  components: {
    FileUpload
  },
  data() {
    return {
      autoDeleteList: [{
        label: '关闭',
        value: 0,
      },
      {
        label: '1天',
        value: 1,
      },
      {
        label: '3天',
        value: 3,
      },
      {
        label: '7天',
        value: 7,
      },
      {
        label: '1个月',
        value: 30,
      },
      {
        label: '6个月',
        value: 180,
      },
      {
        label: '12个月',
        value: 360,
      }
      ],
      countryListData: [],
      provinceListData: [],
      cityListData: [],
      country: null,
      province: null,
      city: null,
      countryName: null,
      provinceName: null,
      cityName: null,

      address: null,
      addRessList: {
        lazy: true,
        emitPath: true,
        lazyLoad: (node, resolve) => {
          const { level, value } = node;
          console.log(level, value)
          if (level == 0) {
            countryList(value).then(res => {
              // console.log(res)
              const nodes = res.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: !item.child, // 是否为叶子节点
              }));
              console.log(nodes)
              // 通知组件数据加载完成
              resolve(nodes);
            })
          } else if (level == 1) {
            provinceList(value).then(res => {
              // console.log(res)
              const nodes = res.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: !item.child, // 是否为叶子节点
              }));
              // 通知组件数据加载完成
              resolve(nodes);
            })
          } else if (level == 2) {
            cityList(value).then(res => {
              // console.log(res)
              const nodes = res.map((item) => ({
                value: item.id,
                label: item.name,
                leaf: !item.child, // 是否为叶子节点
              }));
              // 通知组件数据加载完成
              resolve(nodes);
            })
          }
        }
      },
      userInfo: {},
      maxSize: 5 * 1024 * 1024,
      action: "/user/upload/image",
      rules: {
        nickname: [{
          required: true,
          message: this.$t('请输入昵称'),
          trigger: 'blur',
        },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: '昵称不能包含特殊字符', trigger: 'blur' },
        { max: 10, message: '昵称长度不能超过10位', trigger: 'blur' }
        ],
        sex: [
          {
            required: true,
            message: this.$t('请选择性别'),
            trigger: 'blur'
          }
        ],
        signature: [{
          required: true,
          message: this.$t('请输入个性签名'),
          trigger: 'blur'
        },
        { max: 100, message: '个性签名长度过长', trigger: 'blur' }]
      }
    }
  },
  methods: {
    changeAddress(selectedIds) {
      // 用来匹配国家、省份、市区，需要重新在接口请求一遍
      console.log(this.provinceListData)
      console.log('选中的值:', selectedIds); // [国家ID, 省份ID, 城市ID]
      // 找到对应的国家、省份和城市名称
      let country = null;
      let province = null;
      let city = null;
      if (selectedIds[0]) country = this.countryListData.find(item => item.value === selectedIds[0]);
      if (selectedIds[1]) province = this.provinceListData.find(item => item.value === selectedIds[1]);
      if (selectedIds[2]) city = this.cityListData.find(item => item.value === selectedIds[2]);
      this.countryName = country ? country.label : null;
      this.provinceName = province ? province.label : null;
      this.cityName = city ? city.label : null;
      console.log(this.countryName)
      console.log(this.provinceName)
      console.log(this.cityName)
    },
    onClose() {
      this.$emit("close");
    },
    onSubmit() {
      this.$refs['settingForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.$http({
          url: "/user/editUser",
          method: "post",
          data: this.userInfo
        }).then(() => {
          // console.log(this.userInfo)
          // 修改缓存
          let userInfo = JSON.parse(localStorage.getItem('userInfo'))
          userInfo.messageDeleteFlag = this.userInfo.messageDeleteFlag
          localStorage.setItem('userInfo', JSON.stringify(userInfo))

          this.$store.commit("setUserInfo", this.userInfo);
          this.$emit("close");
          this.$message.success("修改成功");
          this.$nextTick(() => {
            this.$store.commit("clearMsg", this.userInfo.messageDeleteFlag)
          })
        })
      });
    },
    onUploadSuccess(data, file) {
      this.userInfo.headImage = data.thumbUrl;
      this.userInfo.avatar = data.url;
      this.userInfo.avatarThumb = data.thumbUrl
    }
  },
  props: {
    visible: {
      type: Boolean
    }
  },
  mounted() {

  },
  computed: {
    imageAction() {
      return `/user/upload/image`;
    },
    currLanguage() {
      return localStorage.getItem('locale')
    },
  },
  watch: {
    visible: function (newData, oldData) {
      // 深拷贝
      let mine = this.$store.state.userStore.userInfo;
      console.log(mine)
      this.userInfo = JSON.parse(JSON.stringify(mine));
    }
  }
}
</script>

<style lang="scss">
.setting {
  .el-form {
    padding: 10px 0 0 10px;
  }

  .avatar-uploader {
    --width: 112px;

    .el-upload {
      border: 1px dashed #d9d9d9 !important;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: var(--width);
      height: var(--width);
      line-height: var(--width);
      text-align: center;
    }

    .avatar {
      width: var(--width);
      height: var(--width);
      display: block;
    }
  }
}
</style>
